package xwj.example.demo.aspect;

import lombok.Data;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


@Data
public class ApiMetric {
    int minExecutionTime = 10000000;

    int maxExecutionTime = 0;

    int executionCount = 0;

    int totalExecutionTime = 0;

    Map<String, Integer> exceptionCountMap = Collections.synchronizedMap(new HashMap<>());

    public void addTime(int time) {
        totalExecutionTime += time;
        if(time > maxExecutionTime){
            maxExecutionTime = time;
        }
        if(time < minExecutionTime){
            minExecutionTime = time;
        }
    }
    public void addExecution(){
        executionCount++;
    }

    public void reduceExecution(){executionCount--;}
    public void addException(Throwable e){
        String exception=e.getClass().getName();
        Integer exceptionCount=exceptionCountMap.get(exception);
        if(exceptionCount==null){
            exceptionCountMap.put(exception,1);
        }
        else{
            exceptionCountMap.put(exception,exceptionCount+1);
        }
    }
    @Override
    public String toString(){
        String result="";
        result+="调用次数："+executionCount+"\n";
        result+="最长响应时间："+maxExecutionTime+"\n";
        result+="最短响应时间："+minExecutionTime+"\n";
        result+="平均响应时间："+(float)totalExecutionTime/executionCount+"\n";
        if(!exceptionCountMap.isEmpty()){
        result+="各异常发生的次数：\n";
        Set<Map.Entry<String,Integer>> set=exceptionCountMap.entrySet();
        for(Map.Entry<String,Integer> entry : set){
            result+=entry.getKey()+" : "+entry.getValue()+"\n";
        }
        }
        return result;
    }
}
